/**
 * 模态框
 */
module.exports = function($scope, $state, $modalInstance, $resource, roleInfo){

    //加载角色已绑定的模板
    $scope.loadDict = function () {
        $resource('/api/as/sc/dict/getDictForRole', {}, {}).save({'role_id': roleInfo.id}, function (res) {
            if (res.errcode === 0) {
                //两边加逗号,方便字符串判断,防止有部分重复内容,出现判断失误
                var temp = ',' + res.data.bind_dict + ',';
            }
            init(temp);
        });
    };
    $scope.loadDict();

    //初始化查询全部模板
    function init(bind_dict){
        $resource('/api/as/sc/dict/dictbytypelist', {}, {}).save({'type': 'sale_category'}, function (res) {
            if (res.errcode === 0) {
                $scope.dict_list = res.data;
                if(bind_dict){
                    angular.forEach($scope.dict_list, function(item){
                        var index = bind_dict.indexOf(',' + item.value + ',');
                        if(index != -1){
                            item.sel = true;
                        }
                    });
                }
            } else {
                alert(res.errmsg);
            }
        });
    };

    //选择全部模板
    $scope.selAll = function () {
        angular.forEach($scope.dict_list, function(item){
            item.sel = $scope.all? true : false;
        });
    };

    //确定
    $scope.ok = function () {
        var selected_dict = [];
        angular.forEach($scope.dict_list, function(item){
            if(item.sel){
                selected_dict.push(item.value);
            }
        });
        var para = {
            'role_id' : roleInfo.id,
            'bind_dict' : selected_dict.toString()
        }
        $resource('/api/as/sc/dict/addDictForRole', {}, {}).save(para, function (res) {
            if (res.errcode !== 0) {
                alert(res.errmsg);
            }
            //关闭模态框
            $modalInstance.close();
		});
    };

    //取消
    $scope.cancel = function () {
        $modalInstance.dismiss('cancel');
    };


};